<template>
  <div class="wh100">
    <el-upload action="#" class="avatar-uploader upload-border" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="upload">
      <el-image v-if="imageUrl" fit="scale-down" :src="imageUrl" class="avatar" />
      <div v-else class="upload-icon">
        <i class="el-icon-camera-solid avatar-uploader-icon" style="font-size: 60px"></i>
        <span>支持jpg,png格式</span>
        <div style="margin-top: 102px">
          <span>点击上传图片</span>
        </div>
      </div>
    </el-upload>
  </div>
</template>

<script>
import { uploadImg } from "@/api/home";
import urlToCanvas from "@/utils/util.js";
export default {
  props: {
    imageUrl: {
      type: String,
      default: ""
    },
    path: {
      type: String,
      default: () => {
        return "";
      }
    }
  },
  // data() {
  //   return {
  //     imageUrl: "",
  //     path: "",
  //   };
  // },

  methods: {
    resetImage() {
      // eslint-disable-next-line vue/no-mutating-props
      this.imageUrl = "";
      // eslint-disable-next-line vue/no-mutating-props
      this.path = "";
    },
    async upload(params) {
      let formdata = new FormData();
      formdata.append("file", params.file);

      let res = await uploadImg(formdata);
      // eslint-disable-next-line vue/no-mutating-props
      this.path = res.data.path;
      urlToCanvas(res.data.url)
        .then(data => {
          // eslint-disable-next-line vue/no-mutating-props
          this.imageUrl = data;
          this.$emit("upload", {
            path: this.path,
            imageUrl: this.imageUrl
          });
        })
        .catch(err => {
          console.log(err, "图片错误信息");
        });
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG,PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>

<style lang="scss" scoped>
.upload-border {
  border: 1px dashed #d9d9d9 !important;
}
.upload-icon {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-top: 98px;
  color: #5e5e66;
}

.avatar {
  width: 316px;
  height: 316px;
  display: block;
  object-fit: cover;
}
</style>

<style lang="scss">
.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  // width: 200px;
  // height: 200px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  // width: 178px;
  // height: 178px;
  // line-height: 178px;
  text-align: center;
}
</style>
